# !/usr/bin/python3
# -*-coding:utf-8-*-
# Author: sanra
# CreatDate: 2021/1/8 11:10
# Description:

import pika


def fib(n: int):
    return n + 1


def on_request(ch, method, props, body):
    n = int(body)
    print("生产端数据：%s" % (n,))
    response = fib(n = n)
    print("消费端数据：%s" % (response,))

    if props.reply_to is None:
        props.reply_to = ''

    ch.basic_publish(exchange = '',
                     routing_key = props.reply_to,
                     properties = pika.BasicProperties(correlation_id = props.correlation_id),

                     body = str(response))
    ch.basic_ack(delivery_tag = method.delivery_tag)


if __name__ == '__main__':
    credentials = pika.PlainCredentials('guest', 'guest')
    connection = pika.BlockingConnection(pika.ConnectionParameters(
        host = 'localhost', port = 5672, virtual_host = '/', credentials = credentials))
    channel = connection.channel()
    channel.queue_declare(queue = 'rpc_queue', exclusive = False)
    channel.basic_qos(prefetch_count = 1)
    channel.basic_consume(on_message_callback = on_request, queue = 'rpc_queue')
    print("消费端已就绪")
    channel.start_consuming()
